package logger

import (
	"os"
	"path"
	"path/filepath"
	"runtime"
	"strings"
)

var RootPath string

func init() {
	RootPath = getRootPath()
}

// GetFilePath 获取文件路径
func GetFilePath(addPath string) string {
	return RootPath + addPath
}

/*
----------------------------------------- 获取项目根目录 -----------------------------------------
*/

// getRootPath 获取项目根路径
func getRootPath() string {
	dir := getCurAbsPathByGoBuild()
	if strings.Contains(dir, getTmpDir()) {
		dir = getCurAbsPathByGoRun()
	}
	res, _ := filepath.Split(dir)
	return res
}

// 获取系统临时目录
func getTmpDir() string {
	dir := os.Getenv("TEMP")
	if dir == "" {
		dir = os.Getenv("TMP")
	}
	res, _ := filepath.EvalSymlinks(dir)
	return res
}

// 获取当前执行文件的绝对路径(go build)
func getCurAbsPathByGoBuild() string {
	exePath, _ := os.Executable()
	res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
	return res
}

// 获取当前执行文件的绝对路径(go run)
func getCurAbsPathByGoRun() string {
	var abPath string
	_, filename, _, ok := runtime.Caller(0)
	if ok {
		abPath = path.Dir(filename)
	}

	return abPath
}
